package com.handong.handserialprogram.utils;

import org.apache.mina.core.buffer.IoBuffer;

import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * Created by userKey on 2017/6/27.
 */

public class MinaUtil {

    private static final String DEFAULT_ENCODING = "UTF-8";

    public static String ioBufferToString(IoBuffer ioBuffer) {
        Charset charset = Charset.forName(DEFAULT_ENCODING);

        CharsetDecoder decoder = charset.newDecoder();

        try {
            return ioBuffer.getString(decoder);
        } catch (CharacterCodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String ioBufferToStringByByte(IoBuffer buffer) {
        byte[] temp = new byte[buffer.limit()];
        buffer.get(temp);

        int len = temp.length;
        StringBuilder builder = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            builder.append((char) temp[i]);
        }
        return builder.toString();
    }
}
